package com.oocl.listener;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.memory.SystemMemory;
import com.oocl.pojo.Protocol;
import com.oocl.util.CommonURL;
import com.oocl.util.DESUtil;
import com.oocl.util.HTTPConnUtil;

/**
 * Application Lifecycle Listener implementation class SystemListener
 *
 */
@WebListener
public class SystemListener implements ServletContextListener {
	private String address = CommonURL.GET_BAN_LIST;
	private SystemMemory systemMemory=null;

    public SystemListener() {
    	systemMemory = SystemMemory.getInstance();
    }

    public void contextInitialized(ServletContextEvent sce) {
        String result = HTTPConnUtil.sendGet(address);
        if (result==null) {
			HTTPConnUtil.setRun(false);
			
		}else {
	        Protocol protocol = null;
	        List<String> banList = null;
	        try {
	        	if(!result.equals("")){
	        		result = new DESUtil().decrypt(result,"UTF-8");
					protocol = new ObjectMapper().readValue(result, Protocol.class);
					banList = (List<String>) protocol.getMsgObj();
					systemMemory.addBanLists(banList);
	        	}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JsonParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
        
    }
    
    public void contextDestroyed(ServletContextEvent sce) {
    }
	
}
